<template>
  <view class="cart" :class="{ 'pt-80': isStore }">
    <view class="address-box" v-if="isStore">
      配送至：{{ storeInfo.address }}
    </view>
    <my-cart
      ref="shopCart"
      :selectKey="selectKey"
      :cart-list="cartList"
      :select-cart-list="selectCartList"
      @operateCount="operateCount"
      @triggerSelect="triggerSelect"
      @triggerSelectAll="triggerSelectAll"
      @toDetail="toDetail"
      @submit="submit"
      @selection="handleSelection"
      @cartDelete="cartDelete"
    ></my-cart>
    <my-variants
      v-model:show="variantShow"
      :productId="productId"
    ></my-variants>
    <my-tabbar current-page="/pages/index/cart"></my-tabbar>
  </view>
</template>

<script>
import { addStore } from "@/common/apis/goods.js";
import { mapState } from "vuex";
export default {
  data() {
    return {
      selectKey: "id",
      selectCartList: [],
      variantShow: false,
      productId: null,
    };
  },
  computed: mapState({
    cartList: (state) => state.cart.list,
    isStore: (state) => state.user.isStore,
    storeInfo: (state) => state.user.storeInfo,
  }),
  methods: {
    submit() {
      const selectList = this.cartList.filter((item) =>
        this.selectCartList.includes(item[this.selectKey])
      );
      if (selectList.length) {
        if (!this.$store.state.deliver.list.length) {
          uni.showModal({
            content: "请先添加收货地址",
            cancelText: "取消",
            confirmText: "去添加",
            showCancel: true,
            success: (res) => {
              if (res.confirm) {
                uni.$u.route({
                  url: "/pages/user/deliver/form",
                  params: {
                    type: "add",
                  },
                });
              }
            },
          });
        } else {
          this.$store.commit("setSelectOrdersList", selectList);
          uni.$u.route({
            url: "/pages/order/confirm",
          });
        }
      } else {
        uni.$u.toast("请选择商品");
      }
    },
    async handleSelection() {
      const selectList = this.cartList.filter((item) =>
        this.selectCartList.includes(item[this.selectKey])
      );
      if (selectList.length) {
        const promises = [];
        selectList.forEach((cart) => {
          promises.push(
            addStore({
              product_id: cart.product.id,
              lines: [
                {
                  variant_id: cart.variant.id,
                  amount: cart.variant.sale_price,
                },
              ],
            })
          );
        });
        uni.showLoading({
          title: "加入云店中",
          mask: true,
        });
        try {
          await Promise.all(promises);
          this.selectCartList = [];
          await this.fetchBatchDeleteCart(selectList);
          this.$store.dispatch("fetchCartList");
          uni.$u.toast("已加入云店");
        } catch (error) {
          uni.hideLoading();
          uni.$u.toast("加入云店失败");
        }
      } else {
        uni.$u.toast("请选择商品");
      }
    },
    async fetchBatchDeleteCart(selectList) {
      const promises = [];
      // 遍历选中的商品列表，创建删除购物车项的 Promise 数组
      selectList.forEach((i) => {
        promises.push(this.$store.dispatch("fetchDelCart", i.id));
      });
      // 并行执行所有删除操作
      return await Promise.all(promises);
    },
    toDetail(item) {
      uni.navigateTo({
        url: `/pages/goods/detail?id=${item.product.id}`,
      });
      console.log("-toDetail-", item);
    },
    cartDelete(index) {
      uni.showModal({
        title: "提示",
        content: "是否继续删除？",
        success: (res) => {
          if (res.confirm) {
            const id = this.$store.state.cart.list[index].id;
            if (id) {
              this.$store.dispatch("fetchDelCart", id);
              this.$refs.shopCart.calculatePrice();
            }
          }
        },
      });
    },
    async operateCount(params) {
      const { item, type } = params;
      if (type === "add") {
        // 添加数量
        await this.$store.dispatch("fetchAddCart", {
          product_id: item.product.id,
          quantity: 1,
          variant_id: item.variant.id,
        });
        item.quantity += 1;
      } else if (type === "del") {
        // 减少数量
        if (item.quantity > 1) {
          if (item.quantity <= item.product.min_sale_quantity) {
            uni.showModal({
              title: "删除提示",
              confirmColor: "#f0c785",
              content: `是否确认从购物车中删除此商品?`,
              success: (res) => {
                if (res.confirm) {
                  this.$store.dispatch("fetchDelCart", item.id);
                }
              },
            });
          } else {
            await this.$store.dispatch("fetchAddCart", {
              product_id: item.product.id,
              variant_id: item.variant.id,
              quantity: -1,
            });
            item.quantity -= 1;
          }
        } else {
          uni.showModal({
            content: "继续减少商品数量将会移除购物车，是否继续？",
            success: async (res) => {
              if (res.confirm) {
                await this.$store.dispatch("fetchDelCart", item.id);
              }
            },
          });
          // 数量为1减少数量可认为是删除操作
        }
      }
      this.$refs.shopCart.calculatePrice();
    },
    triggerSelect(item) {
      const findIndex = this.selectCartList.findIndex(
        (t) => t === item[this.selectKey]
      );
      if (findIndex === -1) {
        this.selectCartList.push(item[this.selectKey]);
      } else {
        this.selectCartList.splice(findIndex, 1);
      }
    },
    triggerSelectAll(selectAll) {
      if (selectAll) {
        this.selectCartList = [];
      } else {
        this.selectCartList = this.cartList.map((item) => item[this.selectKey]);
      }
    },
  },
  onShow() {
    if (this.$store.state.user.isStore) {
      this.$store.dispatch("fetchCartList");
    }
  },
  onHide() {
    this.selectCartList = [];
  },
};
</script>

<style lang="scss" scoped>
.cart {
  padding-bottom: 150rpx;

  &.pt-80 {
    padding-top: 80rpx;
  }

  .address-box {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 20rpx;
    background-color: #ffffff;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 9999;
  }
}
</style>
